<?php
namespace app\api\service;

use app\api\model\Member as MemberModel;
use app\api\model\ZhBalanceLog as ZhBalanceLogModel;
use app\api\model\MoneyBalanceLog;
use think\facade\Db;

class ZhBalanceService{

    //处理虚拟币的变动情况
    public static function updateMoneyBalanceLog($wxapp_id, $uid, $money, $type, $remark, $orderNo){
        $sUser = MemberModel::find($uid);
        $data = [
            'u_id'          => $uid,
            'wxapp_id'      => $wxapp_id,
            'start_balance' => $sUser['balance'],
            'end_balance'   => $sUser['balance'] +$money,
            'type'          => $type, //'收入',
            'remake'        => $remark, //'对方拒绝交换',
            'create_time'   => time(),
            'num'           => $money,
            'order_no' => $orderNo
        ];
        if($type == '收入') {
            $data['end_balance'] = $sUser['balance'] + $money;
        }else{
            if($remark == '提现被拒绝'){//如果提现被拒，收入流水设为无效，推广页面统计数据的时候要用
                $data['invalid'] = 1;
            }
            $data['end_balance'] = $sUser['balance'] - $money;
        }
        MoneyBalanceLog::insert($data);
        if($type == '收入'){
            $balance = Db::raw('balance + ' . $money);
        }else if($type == '支出'){
            $balance = Db::raw('balance - ' . $money);
        }
        return MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])
            ->update(['balance' => $balance]);
    }

    //处理虚拟币的变动情况
    public static function updateVirtualBalanceLog($wxapp_id, $uid, $money, $type, $remark){
        $sUser = MemberModel::find($uid);
        $data = [
            'u_id'          => $uid,
            'wxapp_id'      => $wxapp_id,
            'start_balance' => $sUser['virtual_currency_balance'],
            'end_balance'   => $sUser['virtual_currency_balance'] +$money,
            'type'          => $type, //'收入',
            'remake'        => $remark, //'对方拒绝交换',
            'create_time'   => time(),
            'num'           => $money
        ];
        ZhBalanceLogModel::insert($data);
        if($type == '收入'){
            $virtual_currency_balance = Db::raw('virtual_currency_balance + ' . $money);
        }else if($type == '支出'){
            $virtual_currency_balance = Db::raw('virtual_currency_balance - ' . $money);
        }
        MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])
            ->update(['virtual_currency_balance' => $virtual_currency_balance]);
    }
}